package com.visionet.waveletData.web.service.robot;

import com.visionet.waveletData.web.common.utils.PageInfo;
import com.visionet.waveletData.web.entity.robot.Robot;
import com.visionet.waveletData.web.repository.account.UserDao;
import com.visionet.waveletData.web.repository.group.GroupDao;
import com.visionet.waveletData.web.repository.robot.RobotDao;
import com.visionet.waveletData.web.vo.RobotVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by hxpeng on 2017/1/10.
 */

@Service
public class RobotService {

    private final static Logger logger = LoggerFactory.getLogger(RobotService.class);

    @Autowired
    private RobotDao robotDao;

    @Autowired
    private GroupDao groupDao;

    @Autowired
    private UserDao userDao;

    public PageImpl<RobotVo> findAllRobotVo(RobotVo robotVo){
        if(robotVo == null){
            throw new NullPointerException("查询实体为空！！！");
        }
        PageInfo pageInfo = robotVo.getPageInfo();
        PageRequest pageRequest = null;
        if(robotVo.getPageInfo()==null){
            pageInfo = new PageInfo();
            pageInfo.setPageSize(10);
        }
        pageRequest=getPageRequestInfo(pageInfo);
        PageImpl<RobotVo> page = robotDao.findPageRobot(robotVo,pageRequest);
        return page;
    }

    public PageImpl<RobotVo> findPageRobotInGroupAddMethod(RobotVo robotVo){
        if(robotVo == null){
            robotVo = new RobotVo();
        }
        try {
            PageInfo pageInfo = robotVo.getPageInfo();
            PageRequest pageRequest = null;
            if(pageInfo == null){
                pageInfo = new PageInfo();
                pageInfo.setPageSize(10);
            }
            pageRequest=getPageRequestInfo(pageInfo);
            PageImpl<RobotVo> page = robotDao.findPageRobotInGroupAddMethod(robotVo,pageRequest);
            return page;
        }catch (Exception e){
            throw new RuntimeException("异常,查询机器人失败！");
        }

    }

    private PageRequest getPageRequestInfo(PageInfo pageInfo){
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        return new PageRequest(pageInfo.getPageNumber() - 1,pageInfo.getPageSize(), sort);
    }

    public String deleteRobot(String robotId){
        if(robotDao.findCountByRobotId(robotId) > 0){
            throw new RuntimeException("该机器人已被分配到其他分组");
        }
        Robot robot = robotDao.findOne(Long.parseLong(robotId));
        if(robot!=null){
            robot.setIs_deleted("1");
            robotDao.save(robot);
            return "1";
        }else{
            return "0";
        }
    }

    @Transactional
    public String importRobotData(List<Robot> list, String companyId, String operateType){
        StringBuffer resultMsg = new StringBuffer();
        //删除机器人时，不存在机器人的编码
        int robotNotFound = 0;
        StringBuffer nfRobotNumberStr = new StringBuffer();

        int hadRobotSize = 0;
        StringBuffer stringBuffer = new StringBuffer("");

        Date currentDate = new Date();
        String robotNumber = "";
        int listSize = list.size();
        try {
            for(Robot robot : list){
                robotNumber = robot.getRobotNumber();
                Robot entity = robotDao.findOneByRobotNumberAndCompanyId(robotNumber,companyId);
                if(operateType.equals("delete") && entity == null){
                    robotNotFound ++;
                    nfRobotNumberStr.append(robotNumber+",");
                    continue;
                }
                if(entity != null){
                    if(operateType.equals("delete")){
                        int count = robotDao.checkRobotIsInPlan(robotNumber);
                        if(count > 0){
                            //记录删除操作时，不能删除的机器人编号
                            stringBuffer.append(robot.getRobotNumber()+",");
                            hadRobotSize ++;
                        }else{
                            entity.setIs_deleted("1");
                            robotDao.save(entity);
                        }
                        continue;
                    }
                    //记录重复导入的机器人编号和数量
                    stringBuffer.append(robot.getRobotNumber()+",");
                    hadRobotSize ++;
                }else{
                    if(operateType.equals("create")){
                        robot.setCreateBy("import");
                        robot.setCreateDate(currentDate);
                        robot.setUpdateDate(null);
                        robot.setUpdateBy(null);
                        robot.setInGroupId(null);
                        robot.setCompanyId(companyId);
                        robot.setIs_deleted("0");
                        robotDao.save(robot);
                    }
                }
            }

            if(operateType.equals("delete")){
                resultMsg.append("删除完成!总共" + listSize + "个,");
                resultMsg.append("其中失败"+ (hadRobotSize+robotNotFound) +"个，");
                if(hadRobotSize > 0){
                    resultMsg.append(hadRobotSize+"个机器人已被部署到播放计划中。");
                }
                if(robotNotFound > 0){
                    resultMsg.append(robotNotFound + "个机器人未找到。");
                }
                if(robotNotFound > 0 || hadRobotSize > 0){
                    resultMsg.append("失败机器人编号：" + stringBuffer.toString()).append(nfRobotNumberStr);
                }
            }else{
                resultMsg.append("导入完成!总共" + listSize + "个,");
                resultMsg.append("失败"+ (hadRobotSize) +"个。");
                if(hadRobotSize > 0){
                    resultMsg.append(hadRobotSize+"个机器人已被存在！");
                    resultMsg.append("已存在机器人编号：" + stringBuffer.toString());
                }
            }
            logger.info(resultMsg.toString());
        }catch (Exception e){
            throw new RuntimeException("保存机器人失败：" + e);
        }
        return resultMsg.toString();
    }


}
